﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Assets;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using System;

//Main Controller 
public class MainBehavior : MonoBehaviour {

    private Socket inputService;
    private const string ipAddr = "127.0.0.1";
    private const int port = 10001;

    private static byte[] inputMsgBuffer = new byte[500];

	// Use this for initialization
	void Start () {
        GameObject info = GameObject.Find("info");
        Log.init(info);
        Log.write("init socket...");
        inputService = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPAddress ip = IPAddress.Parse(ipAddr);
        inputService.Bind(new IPEndPoint(ip, port));
        //设置排队等待连接 的最大数量
        inputService.Listen(100);
        Log.write("socket Listen...");
        inputService.BeginAccept(new AsyncCallback(ClientAccepted), inputService);
        Log.write("waiting connect...");


    }
	
	// Update is called once per frame
	void Update () {
		
	}


    private static void ClientAccepted(IAsyncResult ar)
    {
        var socket = ar.AsyncState as Socket;
        var client = socket.EndAccept(ar);
        Log.write("client connect");
        client.BeginReceive(inputMsgBuffer, 0, inputMsgBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveMsg), client);
        client.BeginAccept(new AsyncCallback(ClientAccepted), socket);
    }

    private static void ReceiveMsg(IAsyncResult ar)
    {
        Log.write("receive msg");
        int length = 0;
        var socket = ar.AsyncState as Socket;
        IPEndPoint clientIP = (IPEndPoint)socket.RemoteEndPoint;
        try
        {

        }catch(Exception e)
        {

        }
    }
}
